package com.example.score.service;

import com.alibaba.fastjson.JSON;
import com.example.score.config.BstaConfig;
import com.example.score.config.ServerConfig;
import com.example.score.dto.AjaxResult;
import com.example.score.utils.HttpUtils;
import com.example.score.utils.WkhtmltopdfUtil;
import com.google.protobuf.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import com.example.score.entity.StudentQuestionPdf;
import com.example.score.mapper.StudentQuestionPdfMapper;

@Slf4j
@Service
public class StudentQuestionPdfService {

    @Value("${bsta.profile}")
    private String pdfPath;


    @Autowired
    private StudentQuestionPdfMapper studentQuestionPdfMapper;
    @Autowired
    private BstaConfig bstaConfig;
    @Autowired
    private ServerConfig serverConfig;


    public int deleteByPrimaryKey(Long id) {
        return studentQuestionPdfMapper.deleteByPrimaryKey(id);
    }

    
    public int insert(StudentQuestionPdf record) {
        return studentQuestionPdfMapper.insert(record);
    }

    
    public int insertSelective(StudentQuestionPdf record) {
        return studentQuestionPdfMapper.insertSelective(record);
    }

    
    public StudentQuestionPdf selectByPrimaryKey(Long id) {
        return studentQuestionPdfMapper.selectByPrimaryKey(id);
    }

    
    public int updateByPrimaryKeySelective(StudentQuestionPdf record) {
        return studentQuestionPdfMapper.updateByPrimaryKeySelective(record);
    }

    
    public int updateByPrimaryKey(StudentQuestionPdf record) {
        return studentQuestionPdfMapper.updateByPrimaryKey(record);
    }

    
    public int updateBatch(List<StudentQuestionPdf> list) {
        return studentQuestionPdfMapper.updateBatch(list);
    }

    
    public int batchInsert(List<StudentQuestionPdf> list) {
        return studentQuestionPdfMapper.batchInsert(list);
    }

    public String pdfDownload(Long studentId, Long subjectId, Long examDetailId) {
        try {
            String url = studentQuestionPdfMapper.selectPdfByStudentId(studentId, subjectId, examDetailId);
            if (ObjectUtils.isEmpty(url)) {
                //需要指定目录下 查找html然后转成pdf 并且上传到服务器，拿到路径
                // 生成日期目录
                String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
                File htmlFile = new File(pdfPath +"/upload/" +datePath + File.separator + examDetailId + "_" + subjectId + "_" + studentId + ".html");
                if (htmlFile.exists()) {
                    // 确保pdf保存到upload目录下
                    String uploadDir = pdfPath + File.separator + "upload" + File.separator + datePath;
                    File directory = new File(uploadDir);
                    if (!directory.exists()) {
                        if (!directory.mkdirs()) {
                            throw new Exception("创建PDF目录失败");
                        }
                    }
                    // PDF文件名
                    String pdfFileName = examDetailId + "_" + subjectId + "_" + studentId + ".pdf";
                    String destPath = uploadDir + File.separator + pdfFileName;
                    boolean b = WkhtmltopdfUtil.convert2(htmlFile.getPath(), destPath);
                    if(b) {
                        // 删除HTML文件
                        if (htmlFile.delete()) {
                            log.info("HTML文件删除成功: {}", htmlFile.getAbsolutePath());
                        } else {
                            log.warn("HTML文件删除失败: {}", htmlFile.getAbsolutePath());
                        }
                        // 构建HTTP访问URL（使用相对路径，因为静态资源已经配置好了）
                        String httpUrl = "/upload/" + datePath + "/" + pdfFileName;
                        StudentQuestionPdf studentQuestionPdf = new StudentQuestionPdf();
                        studentQuestionPdf.setExamDetailId(examDetailId);
                        studentQuestionPdf.setPdfPath(httpUrl);
                        studentQuestionPdf.setSubjectId(subjectId);
                        studentQuestionPdf.setStudentId(studentId);
                        studentQuestionPdf.setCreatedTime(new Date());
                        studentQuestionPdf.setUpdatedTime(new Date());
                        studentQuestionPdfMapper.insert(studentQuestionPdf);
                        return httpUrl;
                    }
                } else {
                    throw new Exception("未找到学生文件，请重新生成");
                }
            }
            return url;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public String fileToUploadHandle(File file) {
        String serverUrl = serverConfig.getUrl() + "/common/upload";
        try {
            Map<String, String> map = new HashMap<>();
            map.put("file", file.getAbsolutePath());
            String result = HttpUtils.sendForm(serverUrl, null, map);
            AjaxResult uploadResult = JSON.parseObject(result, AjaxResult.class);
            if (!uploadResult.get("code").equals(200)) {
                throw new ServiceException("文件上传到服务器失败");
            } else {
                // 文件上传成功，删除本地文件
                if (file.exists()) {
                    if (file.delete()) {
                        log.info("本地文件删除成功: " + file.getAbsolutePath());
                    } else {
                        log.info("本地文件删除失败: " + file.getAbsolutePath());
                    }
                }
            }
            
            // 直接使用服务器返回的url
            return uploadResult.get("url").toString();
        } catch (Exception e) {
            log.error("文件上传异常: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
